/**
 * @file Receiver.java
 *
 * Reads messaged from the Bluetooth receiver.
 * 
 * Author: DKE Aerospace Germany GmbH
 *
 * Copyright 2011 European Commission
 *
 * Licensed under the EUPL, Version 1.1 only (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 * http://ec.europa.eu/idabc/eupl
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 *
 **/
package com.dkeaerospace.egnosdemoapp;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import android.content.Context;
import android.util.Log;

/**
 * @author DKEITAdmin
 * 
 */
public class Receiver {

  Context context;
  FileWriter gpxwriter;
  FileWriter internalLogFilewriter;
  BufferedWriter out;
  LogFiles log;
  private static final String TAG = "EGNOS-SDK";

  /**
   * Receiver Constructor.
   * Constructs an interface to global information of the application
   * that called Receiver class and file writer that writes to a file.
   * 
   * @param context    interface to the global information of the application
   *                   environment.
   * @param gpxwriter   writer to the File named gpxFile.
   * @param internalLogFilewriter  writer to the File named internalLogFile.
   **/
  public Receiver(Context context, FileWriter gpxwriter,
      FileWriter internalLogFilewriter) {
    this.context = context;
    this.gpxwriter = gpxwriter;
    this.internalLogFilewriter = internalLogFilewriter;
    log = new LogFiles(gpxwriter, internalLogFilewriter);
  }

  /**
   * readMessage function
   * Read data from the Bluetooth receiver.
   * 
   * @param receiverByte      The message from the receiver.
   * @return numBytesRead     The number of bytes read.
   **/
  public static int readMessage(final byte[] receiverByte) {
    int numBytesRead = 0;
    GlobalState gsg;
    gsg = BluetoothConnect.getGs();
    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
      Log.e(TAG, "Receiver | ThrdSleep (" + e.getMessage() + ")");
      e.printStackTrace();
    }
    StringBuffer receiverMessage = new StringBuffer("");

    try {
      numBytesRead = gsg.getInputStream().read(receiverByte);
      Utils.toHexCharArray(receiverByte);
      receiverMessage.append(Utils.toHex(receiverByte));
    } catch (Exception e) {
      Log.e(TAG, "Receiver | Receive error: " + e.getMessage());
      e.printStackTrace();
    }

    return numBytesRead;
  }

  /**
   * getNumBytes function
   * Read data from the Bluetooth receiver.
   * 
   * @param receiverByte      The message from the receiver.
   * @return numBytesRead     The number of bytes read.
   **/
  public static int getNumBytes(final byte[] receiverByte) {
    int numBytesRead = 0;
    int dataAvailable = 0;
    GlobalState gsg;

    gsg = BluetoothConnect.getGs();
    if (gsg.getSocket() != null) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        Log.e(TAG, "Receiver | ThrdSleep (" + e.getMessage() + ")");
        e.printStackTrace();
      }

      try {
        dataAvailable = gsg.getInputStream().available();
      } catch (IOException e1) {
        Log.e(TAG, "Receiver | getNumBytes() | No data available: "
            + dataAvailable);
        gsg.setSocket(null);
        numBytesRead = -1;
        e1.printStackTrace();
        return 0;
      }

      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        Log.e(TAG, "Receiver | ThrdSleep (" + e.getMessage() + ")");
        e.printStackTrace();
      }
      //uncomment this part if the application hangs at read.
      // if (dataAvailable != 0) {
      try {

        numBytesRead = gsg.getInputStream().read(receiverByte);

      } catch (Exception e) {
        Log.e(TAG,
            "Receiver | getNumBytes() | Receive error: " + e.getMessage());
        gsg.setSocket(null);
        numBytesRead = -1;
        e.printStackTrace();
      }
      // } else {
      // Log.e(TAG, "Receiver | getNumBytes() | No data available: "
      // + dataAvailable);
      // return 0;
      // }
    } else {
      gsg.setSocket(null);
    }

    return numBytesRead;
  }

  /**
   * sendMessageToReceiver function 
   * Sends a message to receiver, depending on the identifier.
   * 
   * @param message     Message to be sent.
   **/
  protected static int sendMessageToReceiver(final String message) {
    GlobalState gS;
    gS = BluetoothConnect.getGs();
    byte[] command = Utils.generateByteMessage(message);
    int ret = Utils.write(command, gS);
    return ret;
  }

}
